package com.sgb.kjwl.view.ui.adapter.home;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;
import android.widget.ImageView;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.fondesa.recyclerviewdivider.DividerDecoration;
import com.sgb.kjwl.BR;
import com.sgb.kjwl.R;
import com.sgb.kjwl.api.NewAPIManager;
import com.sgb.kjwl.databinding.ItemCarHallSubVideoBinding;
import com.sgb.kjwl.databinding.ItemCarHallVideoBinding;
import com.sgb.kjwl.databinding.ItemVehicleHallBinding;
import com.sgb.kjwl.model.entity.transport.CarHallEntity;
import com.sgb.kjwl.model.entity.transport.SingleItemConstant;
import com.sgb.knowledgeshare.utils.SharePermissionUtils;
import com.swgk.core.base.api.ICallBack;
import com.swgk.core.view.entity.PermissionEntity;
import com.sgb.kjwl.utils.LogisticsPermissionHelper;
import com.sgb.kjwl.utils.NumberUtil;
import com.swgk.core.util.PermissionCheckUtil;
import com.swgk.core.util.UserOperating;
import com.sgb.knowledgeshare.view.activity.HomeShareActivity;
import com.sgb.kjwl.view.ui.activity.self.logistics.InquiryActivity;
import com.sgb.knowledgeshare.view.activity.PlayListActivity;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.base.model.entity.VideoBean;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.dialog.RoundDialog;
import com.im.immodel.IMUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @author: 杨畔
 * @date: 3/3/21 8:10 PM
 * @Description: 车辆大厅适配器
 */
public class CarsHallAdapter extends BaseMultiItemQuickAdapter<CarHallEntity, BaseViewHolder> {
    /**
     * Same as QuickAdapter#QuickAdapter(Context,int) but with
     * some initialization data.
     *
     * @param data A new list is created out of this one to avoid mutable list
     */
    private boolean isSelf = false;

    public CarsHallAdapter(List<CarHallEntity> data) {
        super(data);
        //车辆类别
        addItemType(SingleItemConstant.TYPE_ONE, R.layout.item_vehicle_hall);
        //视频类别
        addItemType(SingleItemConstant.TYPE_TWO, R.layout.item_vehicle_hall_videos);
        //单个视频类别
        addItemType(SingleItemConstant.TYPE_THREE, R.layout.item_car_hall_video);
    }

    public CarsHallAdapter(List<CarHallEntity> data, boolean isSelf) {
        super(data);
        this.isSelf = isSelf;
        //车辆类别
        addItemType(SingleItemConstant.TYPE_ONE, R.layout.item_vehicle_hall);
        //视频类别
        addItemType(SingleItemConstant.TYPE_TWO, R.layout.item_vehicle_hall_videos);
        //单个视频类别
        addItemType(SingleItemConstant.TYPE_THREE, R.layout.item_car_hall_video);
    }

    @Override
    protected void convert(BaseViewHolder helper, CarHallEntity item) {
        switch (item.getItemType()) {
            case SingleItemConstant.TYPE_ONE:
                initCarInfo(helper, item);
                break;
            case SingleItemConstant.TYPE_TWO:
                initVideoList(helper, item);
                break;
            case SingleItemConstant.TYPE_THREE:
                initSingleVideo(helper, item);
                break;
        }
    }

    /**
     * 设置车辆信息
     */
    private void initCarInfo(BaseViewHolder helper, CarHallEntity entity) {
        //设置dataBinding数据
        ItemVehicleHallBinding binding = DataBindingUtil.bind(helper.itemView);
        if (binding == null) return;
        binding.setVariable(BR.viewModel, entity);
        binding.executePendingBindings();
        StringBuilder builder = new StringBuilder();
        if (!TextUtils.isEmpty(entity.getCarTypeName())) {
            builder.append(entity.getCarTypeName()).append("\u0020");
        }
        if (!TextUtils.isEmpty(entity.getHeightHurdle())) {
            builder.append("栏高");
            builder.append(NumberUtil.trim0(entity.getHeightHurdle()));
            builder.append("米/");
        }
        if (!TextUtils.isEmpty(entity.getCarLenName())) {
            builder.append("车长" + entity.getCarLenName());
        }
        if (entity.getWeight() != null) {
            builder.append("\u0020");
            builder.append(NumberUtil.trim0(entity.getWeight()));
            builder.append("吨");
        }

        if (entity.getIsDumper() != null) {
            builder.append("\u0020");
            builder.append(entity.getIsDumper() == 1 ? "自卸" : "非自卸");
        }
        binding.titleView.setText(builder.toString());
        //没有位置信息时隐藏
        if (TextUtils.isEmpty(entity.getProvinceName()) && TextUtils.isEmpty(entity.getCityName()) && TextUtils.isEmpty(entity.getDistrictName())) {
            binding.priceView.setVisibility(View.GONE);
        } else {
            binding.priceView.setVisibility(View.VISIBLE);
            binding.priceView.setText(String.format("%s%s%s", entity.getProvinceName(), entity.getCityName(), entity.getDistrictName()));
        }
        //
        if (entity.getDistance() == null) {
            binding.tvDistance.setText("");
        } else {
            binding.tvDistance.setText(entity.getDistance() < 1000 ? "距您 1km以内" : String.format("距您 %skm", NumberUtil.trim0(entity.getDistance() / 1000)));
        }
        //
        binding.llInvitation.setOnClickListener(v -> {
            if (UserOperating.getInstance().isNotLogged(mContext)) {
                return;
            }
            if (entity != null && !UserOperating.getInstance().IsAuth(mContext, entity.getAuthTime())) {
                return;
            }
            permissionsInterface.setPermissions(entity);
//            invitationClick(entity);
        });
        binding.llChat.setOnClickListener(v -> {
            if (UserOperating.getInstance().isNotLogged(mContext)) {
                return;
            }
            if (entity != null && !UserOperating.getInstance().IsAuth(mContext, entity.getAuthTime())) {
                return;
            }
            chatClick(entity);
        });

        binding.llInquiry.setOnClickListener(v -> {
            if (UserOperating.getInstance().isNotLogged(mContext)) {
                return;
            }
            if (entity != null && !UserOperating.getInstance().IsAuth(mContext, entity.getAuthTime())) {
                return;
            }
            requestPermissions(entity);
        });

        RequestOptions requestOptions = null;
        if (entity.getTerminal() == 1) {
            requestOptions = new RequestOptions()
                    .placeholder(R.mipmap.icon_company_default)//图片加载出来前，显示的图片
                    .fallback(R.mipmap.icon_company_default) //url为空的时候,显示的图片
                    .error(R.mipmap.icon_company_default);//图片加载失败后，显示的图片
        } else if (entity.getTerminal() == 2) {
            requestOptions = new RequestOptions()
                    .placeholder(R.mipmap.icon_team_default_1)//图片加载出来前，显示的图片
                    .fallback(R.mipmap.icon_team_default_1) //url为空的时候,显示的图片
                    .error(R.mipmap.icon_team_default_1);//图片加载失败后，显示的图片
        } else if (entity.getTerminal() == 3) {
            requestOptions = new RequestOptions()
                    .placeholder(R.drawable.geren_person_touxiang)//图片加载出来前，显示的图片
                    .fallback(R.drawable.geren_person_touxiang) //url为空的时候,显示的图片
                    .error(R.drawable.geren_person_touxiang);//图片加载失败后，显示的图片
        }

        if (TextUtils.isEmpty(entity.getRoleName())) {
            binding.teamInfoLayout.setVisibility(View.GONE);
        } else {
            binding.teamInfoLayout.setVisibility(View.VISIBLE);
            binding.teamName.setText(entity.getRoleName());
            Glide.with(mContext).load(entity.getImg()).apply(requestOptions).into(binding.teamImg);
        }
    }

    /**
     * 设置视频信息
     */
    private void initVideoList(BaseViewHolder helper, CarHallEntity entity) {
        RecyclerView recyclerView = helper.getView(R.id.rv_item_vehicle_hall_videos);
        List<VideoBean> videoBeanList = new ArrayList<>();
        videoBeanList.addAll(entity.getVideoList());
        if (videoBeanList.size() >= 6) {
            VideoBean v = new VideoBean();
            v.setType("查看更多视频");
            videoBeanList.add(v);
        }
        CarsHallVideoAdapter adapter = new CarsHallVideoAdapter(videoBeanList);
        recyclerView.setNestedScrollingEnabled(false);
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext, RecyclerView.HORIZONTAL, false));
        if (recyclerView.getItemDecorationCount() == 0) {
            DividerDecoration.builder(mContext)
                    .color(Color.TRANSPARENT)
                    .size(5, TypedValue.COMPLEX_UNIT_DIP)
                    .build()
                    .addTo(recyclerView);
        }
        adapter.bindToRecyclerView(recyclerView);
        adapter.setOnItemClickListener((adapter1, view, position) -> {
            if (adapter.getData().get(position).isCheckMoreVideos()) {
                SharePermissionUtils.getPermissionTwo((Activity) mContext,1);
            } else {
                //视频播放
                Intent intent = new Intent(mContext, PlayListActivity.class);
                intent.putExtra(PlayListActivity.VIDEOLISTBEAN, (Serializable) entity.getVideoList());
                intent.putExtra(PlayListActivity.PSO, position);
                intent.putExtra(PlayListActivity.VIDEOTYPE, "home_bigVideo");
                mContext.startActivity(intent);
            }
        });
    }

    /**
     * 设置单个视频信息
     */
    private void initSingleVideo(BaseViewHolder helper, CarHallEntity entity) {
        //设置dataBinding数据
        ItemCarHallVideoBinding binding = DataBindingUtil.bind(helper.itemView);
        if (binding == null) return;
        if (entity.getVideoList() != null && !entity.getVideoList().isEmpty()) {
            binding.setVariable(BR.viewModel, entity.getVideoList().get(0));
            binding.executePendingBindings();
        }
    }

    /**
     * 获取权限
     *
     * @param entity
     */
    public void requestPermissions(CarHallEntity entity) {
        DialogHelper.showProgressDialog(mContext, "数据获取中...").setCanceledOnTouchOutside(false);
        NewAPIManager.getInstance().getLogisticsAPI().getLogisticsPermissions().enqueue(new ICallBack<BaseEntity<PermissionEntity>>() {
            @Override
            public void onSuccess(BaseEntity<PermissionEntity> data) {
                if(data.isSuccess()){
                    SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.COM_TYPE, data.getData().getUserType());
                    UserOperating.getInstance().setUserInfo(data.getData());
                    inquiryClick(entity);
                }
            }
        });
    }

    /**
     * 询价
     */
    private void inquiryClick(CarHallEntity entity) {
        if (entity == null)
            return;
        if (UserOperating.getInstance().isNotLogged(mContext)) {
            return;
        }
        if (UserOperating.getInstance().isNotOpenFundAccount(mContext, PermissionCheckUtil.KEY_WODEXUNJIA)) {
            return;
        }
        getInquiryPermissions(entity);
    }

    /**
     * 查询询价权限
     *
     * @param entity
     */
    public void getInquiryPermissions(CarHallEntity entity) {
        if (!TextUtils.isEmpty(entity.getDriverAuthNo())) {
            NewAPIManager.getInstance().getLogisticsAPI().getInquiryPermissions(entity.getDriverAuthNo(), "").enqueue(new ICallBack<BaseEntity<Boolean>>() {
                @Override
                public void onSuccess(BaseEntity<Boolean> data) {
                    if(data.isSuccess()){
                        if (data.getData()) {
                            //去询价界面
                            InquiryActivity.startCarInquiry(mContext, String.valueOf(entity.getDriverAuthNo()), entity.getTelphone());
                        } else {
                            MToast.showToast(mContext, "不能对自己发布的车辆进行询价！");
                        }
                    }
                }
            });
        }
    }

    /**
     * 聊天
     */
    private void chatClick(CarHallEntity entity) {
        if (entity != null && !TextUtils.isEmpty(entity.getDriverCreateIm())) {
            IMUtils.getInstance().buildSingleTalking(entity.getDriverCreateIm());
        }
    }

    /**
     * 邀请
     */
    private void invitationClick(CarHallEntity entity) {
        if (!TextUtils.isEmpty(entity.getCompanyNo())) {
            LogisticsPermissionHelper.getInstance().checkPermissionToInvite(mContext, entity.getCompanyNo(), 1);
        } else {
            LogisticsPermissionHelper.getInstance().checkPermissionToInvite(mContext, "", 0);
        }
    }

    private void showTelDialog(String phone) {
        new RoundDialog.Builder(mContext)
                .title("确认呼叫")
                .content(phone)
                .confirm("拨打")
                .cancelable(false)
                .confirmCallback(v -> {
                    Intent intent = new Intent(Intent.ACTION_DIAL);
                    Uri data = Uri.parse("tel:" + phone);
                    intent.setData(data);
                    mContext.startActivity(intent);
                })
                .show();
    }

    /**
     * 车辆大厅视频适配器
     */
    private static class CarsHallVideoAdapter extends BaseQuickAdapter<VideoBean, BaseViewHolder> {

        public CarsHallVideoAdapter(@Nullable List<VideoBean> data) {
            super(R.layout.item_car_hall_sub_video, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, VideoBean entity) {

            if (entity.isCheckMoreVideos()) {
                ((ImageView) helper.getView(R.id.tag_cuxiao)).setImageDrawable(mContext.getResources().getDrawable(R.drawable.check_more_video));
                ((ImageView) helper.getView(R.id.iv_item_car_hall_video)).setImageDrawable(mContext.getResources().getDrawable(R.drawable.gray_radius_bkg));
                (helper.getView(R.id.more_video_text)).setVisibility(View.VISIBLE);
                (helper.getView(R.id.title_view)).setVisibility(View.GONE);
            } else {
                //设置dataBinding数据
                (helper.getView(R.id.title_view)).setVisibility(View.VISIBLE);
                (helper.getView(R.id.more_video_text)).setVisibility(View.GONE);
                ((ImageView) helper.getView(R.id.tag_cuxiao)).setImageDrawable(mContext.getResources().getDrawable(R.mipmap.icn_video_play));
                ItemCarHallSubVideoBinding binding = DataBindingUtil.bind(helper.itemView);
                if (binding == null) return;
                binding.setVariable(BR.viewModel, entity);
                binding.executePendingBindings();
            }

        }
    }
    private PermissionsInterface permissionsInterface;
    public void  setPermissionsInterface(PermissionsInterface permissionsInterface){
        this.permissionsInterface = permissionsInterface;
    }

    public interface PermissionsInterface{
        void setPermissions(CarHallEntity entity);
    }
}
